#!/bin/sh

. /usr/share/libubox/jshn.sh

wps_status(){
	if [ -z $(pidof wps_monitor) ]; then
		CODE=-1; 
		STATUS="stopped"; 
	else
		CODE=$(nvram get wps_proc_status); 
		case $CODE in 
			0) 
				STATUS="init"; 
				;;
			1)
				STATUS="processing"; 
				;;
			2)
				STATUS="success"; 
				;;
			3)
				STATUS="fail"; 
				;;
			4)
				STATUS="timeout"; 
				;;
			7)
				STATUS="msgdone"; 
				;;
		esac
	fi
	json_init
	json_add_int "code" $CODE
	json_add_string "status" $STATUS
	json_dump
}

wps_pbc(){
	if [ -z $(pidof wps_monitor) ]; then
		{ 
			wps_monitor &
		}  &> /dev/null
		sleep 1
	fi
	killall -SIGUSR2 wps_monitor &> /dev/null
}

wps_genpin(){
	json_init
	json_add_string "pin" $(wps_cmd genpin)
	json_dump
}

wps_checkpin(){
	json_load "$1"
	json_get_var PIN "pin"
	if [ "$PIN" == "" ]; then exit 5; fi
	json_init
	if [ $(wps_cmd checkpin "$PIN") != ""  ]; then 
		json_add_boolean "valid" true
	else
		json_add_boolean "valid" false
	fi
	json_dump
}

wps_stapin(){
	json_load "$1"
	json_get_var PIN "pin"
	if [ "$PIN" == "" ]; then exit 5; fi
	wps_cmd addenrollee wl0 sta_pin="$PIN" &> /dev/null
	json_init 
	json_add_string "pin" $PIN
	json_dump
}

wps_setpin(){
	json_load "$1"
	json_get_var PIN "pin"
	if [ "$PIN" == "" ]; then exit 5; fi
	wps_cmd setpin "$PIN" &> /dev/null
	json_init 
	json_add_string "pin" $PIN
	json_dump
}

wps_showpin(){
	json_init
	json_add_string "pin" $(nvram get wps_device_pin); 
	json_dump
}

wps_stop(){
	{ 
		killall -SIGTERM wps_monitor;
		nvram set wps_proc_status=0;
		wps_monitor &
	} &> /dev/null
}

case $1 in 
	.methods) 
		echo "status,pbc,genpin,checkpin,stapin,setpin,showpin,stop"; 
		exit 0
		;;
	status) 
		wps_status
		;;
	pbc) 
		wps_pbc
		;;
	genpin) 
		wps_genpin 
		;;
	checkpin)
		wps_checkpin "$2"
		;;
	stapin)
		wps_stapin "$2"
		;;
	setpin)
		wps_setpin "$2"
		;;
	showpin)
		wps_showpin
		;;
	stop)
		wps_stop
		;;
esac

